package com.example.studentproj.service;

import com.example.studentproj.model.Class1;
import com.example.studentproj.model.Student;
import com.example.studentproj.repository.ClassRepository;
import com.example.studentproj.repository.StudentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class ClassServiceLmpl implements ClassService{

    //依赖注入jpa接口
    @Autowired
    private ClassRepository classRepository;

    @Autowired
    private StudentRepository studentRepository;


    //获取所有班级名称
    @Override
    public List<Class1> getAllClass() {
        return classRepository.findAll();
    }


    //修改班级名称方法实现
    @Override
    public Class1 getClassByid(Long id) {
        Optional<Class1> optional = classRepository.findById(id);
        Class1 class1 = null;
        if( optional.isPresent()){
            class1 = optional.get();
        }else{
            throw new RuntimeException(" 查无此班，请重输入, id :  "+ id);
        }
        return class1;
    }

    //删除班级名称
    @Override
    public void deleteClassByid(Long id) {
        classRepository.deleteById(id);
    }

    //保存班级名称信息
    @Override
    public void saveClass(Class1 class1) {
        classRepository.save(class1);

    }

    @Override
    public Page<Class1> findPaginated1(int pageNo, int pageSize, String sortField, String sortDirection) {
        //设置排序参数，升序ASC/降序DESC？
        Sort sort = sortDirection.equalsIgnoreCase(Sort.Direction.ASC.name())
                ? Sort.by(sortField).ascending()
                : Sort.by(sortField).descending();

        //根据页号/每页记录数/排序依据返回某指定页面数据。
        Pageable pageable = PageRequest.of(pageNo - 1, pageSize, sort);
        return this.classRepository.findAll(pageable);
    }

    @Override
    public void updateClassName(Long id, String newClassName) {
        Optional<Class1> optionalClass = classRepository.findById(id);
        if (optionalClass.isPresent()) {
            Class1 class1 = optionalClass.get();
            class1.setName(newClassName);
            classRepository.save(class1);

            // 同步更新学生信息中的班级名称
            List<Student> students = studentRepository.findByClassName(class1.getName());
            students.forEach(student -> student.setClassName(newClassName));
            studentRepository.saveAll(students);
        } else {
            throw new RuntimeException("查无此班，请重输入, id: " + id);
        }
    }



}
